"use client";

import { useState, useEffect } from 'react';
import { webAPI } from "@/lib/api";
import type { Article } from "@/lib/api";
import Pagination from './Pagination';
import ArticleList from './ArticleList';

interface DiscoverTabsProps {
  initialArticles: Article[];
  initialTotalPages: number;
  categoryId?: number;
}

export default function DiscoverTabs({ initialArticles, initialTotalPages, categoryId }: DiscoverTabsProps) {
  const [activeTab, setActiveTab] = useState<'latest' | 'hot'>('latest');
  const [articles, setArticles] = useState<Article[]>(initialArticles);
  const [totalPages, setTotalPages] = useState(initialTotalPages);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    // 当分类ID变化时，重置页码为1
    setPage(1);
    // 切换分类时，默认加载“最新”数据
    if (activeTab !== 'latest') {
      setActiveTab('latest');
    } else {
      fetchArticles('latest', 1);
    }
  }, [categoryId]);

  useEffect(() => {
    // 仅当页码或Tab变化时，才获取文章
    // (初始化和分类切换时由上面的useEffect处理)
    if (page > 1 || (page === 1 && articles !== initialArticles)) {
      fetchArticles(activeTab, page);
    }
  }, [activeTab, page]);

  const fetchArticles = async (tab: 'latest' | 'hot', pageNum: number) => {
    setLoading(true);
    try {
      const sortOrder = tab; // 直接使用 'latest' 或 'hot'
      const res = await webAPI.getArticles({
        page: pageNum,
        limit: 10,
        categoryId,
        status: true,
        sort: sortOrder,
      });
      if (res.success) {
        setArticles(res.data.articles);
        setTotalPages(res.data.totalPages);
      }
    } catch (error) {
      console.error("Failed to fetch articles:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleTabClick = (tab: 'latest' | 'hot') => {
    setPage(1); // 切换Tab时，重置页码
    setActiveTab(tab);
  };
  
  const handlePageChange = (newPage: number) => {
    setPage(newPage);
  };

  return (
    <div className="bg-white rounded-xl border border-gray-200 shadow-sm">
      {/* Sort Bar */}
      <div className="px-6 py-4 border-b border-slate-200 flex justify-between items-center">
        <div className="flex space-x-6">
          <button 
            onClick={() => handleTabClick('latest')}
            className={`font-bold !text-base relative transition-colors duration-200 ${activeTab === 'latest' ? 'text-blue-600' : 'text-slate-500 hover:text-blue-600'}`}
          >
            最新
            {activeTab === 'latest' && <span className="absolute -bottom-4 left-1/2 -translate-x-1/2 w-4 h-0.5 bg-blue-600"></span>}
          </button>
          <div className='w-2 h-0.5'></div>
          <button 
            onClick={() => handleTabClick('hot')}
            className={`font-bold !text-base relative transition-colors duration-200 ${activeTab === 'hot' ? 'text-blue-600' : 'text-slate-500 hover:text-blue-600'}`}
          >
            热门
            {activeTab === 'hot' && <span className="absolute -bottom-4 left-1/2 -translate-x-1/2 w-4 h-0.5 bg-blue-600"></span>}
          </button>
        </div>
      </div>

      {/* Articles List */}
      <div className="min-h-[500px]">
        {loading ? (
          <div className="p-12 text-center text-gray-500">加载中...</div>
        ) : articles.length === 0 ? (
          <div className="p-12 text-center text-gray-500">此分类下暂无文章</div>
        ) : (
          <ArticleList articles={articles} />
        )}
      </div>

      {/* Pagination */}
      <Pagination
        currentPage={page}
        totalPages={totalPages}
        onPageChange={handlePageChange}
      />
    </div>
  );
} 